<!--
 * @Description: ------------ fileDescription -----------
 * @Author: snows_l snows_l@163.com
 * @Date: 2024-08-09 15:52:19
 * @LastEditors: snows_l snows_l@163.com
 * @LastEditTime: 2025-07-02 09:27:14
 * @FilePath: \BLOG\src\components\musicPlayer\index.vue
-->
<template>
  <div class="music-player-components-wrap">
    <audio ref="audioRef" style="display: none" preload="true" :src="state.currentMusic.src"></audio>
    <div class="cover-wrap">
      <div class="cover-img-wrap">
        <LImg class="cover-img" isSpin :isText="false" :class="{ 'rotate-play': state.isPlaying }" :src="state.currentMusic.img || defaultCover" alt="" />
        <div class="paly-pause pointer" @click="handleCoverControl">
          <i v-if="state.isPlaying" class="iconfont icon-zanting"></i>
          <i v-else class="iconfont icon-bofang"></i>
        </div>
      </div>
    </div>
    <div class="contral-music-wrap">
      <div class="contral-music-content" v-if="musicList.length > 0">
        <div class="music-name">{{ state.currentMusic.title }}{{ state.currentMusic.artist ? '—' + state.currentMusic.artist : '' }}</div>
        <!-- <div class="custom-progress">
          <span class="yin">
            <input v-if="true" type="range" name="progress" id="progress" max="100" min="0" v-model="state.progress" @change="handleProgressChange" />
          </span>
          <span class="time" style="font-size: 12px">
            {{ Math.floor(state.currentTime / 60).toFixed(0).length == 1 ? '0' : '' }}{{ Math.floor(state.currentTime / 60) }} :
            {{ Math.floor(state.currentTime % 60).toFixed(0).length == 1 ? '0' : '' }}{{ Math.floor(state.currentTime % 60) }} /
            {{ state.duration ? (Math.floor(state.duration / 60).toFixed(0).length == 1 ? '0' : '') : '0' }}{{ state.duration ? Math.floor(state.duration / 60) : 0 }} :
            {{ state.duration ? (Math.floor(state.duration % 60).toFixed(0).length == 1 ? '0' : '') : '0' }}{{ state.duration ? Math.floor(state.duration % 60) : 0 }}
          </span>
        </div> -->
        <div class="progress-time">
          {{ Math.floor(state.currentTime / 60).toFixed(0).length == 1 ? '0' : '' }}{{ Math.floor(state.currentTime / 60) }} :
          {{ Math.floor(state.currentTime % 60).toFixed(0).length == 1 ? '0' : '' }}{{ Math.floor(state.currentTime % 60) }} /
          {{ state.duration ? (Math.floor(state.duration / 60).toFixed(0).length == 1 ? '0' : '') : '0' }}{{ state.duration ? Math.floor(state.duration / 60) : 0 }} :
          {{ state.duration ? (Math.floor(state.duration % 60).toFixed(0).length == 1 ? '0' : '') : '0' }}{{ state.duration ? Math.floor(state.duration % 60) : 0 }}
        </div>
        <div class="contral-wrap">
          <i @click="handleControl('mute')" v-if="state.isMute" class="pointer iconfont icon-jingyin"></i>
          <i @click="handleControl('mute')" v-else class="pointer iconfont icon-cancelMute-quxiaojingyin"></i>
          <i @click="handleControl('prev', true)" class="pointer iconfont icon-shangyigeshangyiqu"></i>
          <i @click="handleControl('pause', true)" v-if="state.isPlaying" class="pointer iconfont icon-zanting"></i>
          <i @click="handleControl('play', true)" v-else class="pointer iconfont icon-bofang"></i>
          <i @click="handleControl('next', true)" class="pointer iconfont icon-xiayigexiayiqu"></i>
          <i @click="handleTo('/play/mp3')" class="pointer iconfont icon-a-yinlebofangliebiaoyinle kbn-custom" data-tip="点击前往 「音乐列表」！"></i>
          <i @click="handlePlayerTop" :class="{ isTop: state.playerTop }" class="pointer iconfont icon-pin kbn-custom" data-tip="点击钉在 「页面上方」！"></i>
        </div>

        <div class="custom-progress custom-volume">
          <span class="yin pointer">
            <input v-if="true" type="range" name="volume" id="volume" max="100" min="0" v-model="state.volumeB" @change="handleVolumeChange" />
          </span>
          <span class="volume-time" style="font-size: 12px">{{ state.volumeB }}%</span>
        </div>
      </div>
      <div class="empty-wrap" v-else>
        <img class="empty-img" src="@/assets/images/common/empty.png" alt="" />
        <span>暂无歌曲</span>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { getMusicList } from '@/api/music';
import defaultCover from '@/assets/images/common/default_cover.png';
import $bus from '@/bus';
import router from '@/router';
import { useAppStore } from '@/store/app';
import { CustomMessage, getBackstageurl } from '@/utils/common';
import _ from 'lodash';
import { onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';

const emits = defineEmits(['music-status', 'clickList', 'query', 'playMusic', 'fullscreen']);

const props = defineProps({
  currentMusicId: {
    type: Number,
    default: 0
  },
  isMobi: {
    type: Boolean,
    default: false
  }
});

const store = useAppStore();
const audioRef = ref();
const musicList = ref([]);

const isUserInteraction = ref(false);

const state = reactive({
  currentIndex: 0,
  currentMusic: {
    title: '',
    artist: '',
    img: '',
    src: '',
    type: '',
    id: ''
  },
  isPlaying: false,
  isHandlePlayed: false,
  isMute: false,
  volume: 1,
  volumeB: 100,
  duration: 0,
  currentTime: 0,
  progress: 0,
  isLoading: true,
  playList: [],
  playerTop: store.playerTop
});

const getMusicListFn = () => {
  let serverUrl = store.projectConfig.bsServerUrl;
  getMusicList({ isUnPage: false }).then(res => {
    musicList.value = res.data.map(item => {
      let cover = '';
      if (item.cover) cover = import.meta.env.VITE_CURRENT_ENV == 'dev' ? import.meta.env.VITE_DEV_BASE_SERVER + item.cover : serverUrl + item.cover;
      return {
        id: item.id,
        title: item.title,
        artist: item.artist,
        type: item.type,
        img: cover,
        src: import.meta.env.VITE_CURRENT_ENV == 'dev' ? import.meta.env.VITE_DEV_BASE_SERVER + item.src : serverUrl + item.src
      };
    });
    store.SET_MUSIC_LIST(musicList.value);
    state.currentIndex = musicList.value.findIndex(item => item.id == localStorage.getItem('currentMusicId') || 0);
    if (state.currentIndex === -1) state.currentIndex = 0;
    state.currentMusic = musicList.value.length && musicList.value[state.currentIndex];
  });
};

const initGetMusicList = () => {
  if (store.musicList.length) {
    musicList.value = store.musicList;
    state.currentIndex = musicList.value.findIndex(item => item.id == localStorage.getItem('currentMusicId') || 0);
    if (state.currentIndex === -1) state.currentIndex = 0;
    state.currentMusic = musicList.value.length && musicList.value[state.currentIndex];
  } else {
    getMusicListFn();
  }
};
initGetMusicList();

// 跳转到指定页面
const handleTo = (path: string) => {
  router.push(path);
  if (path == '/play/mp3') {
    emits('query', true);
  }
};

// 控制音量 以及静音/取消静音
const controlVolume = (type: string) => {
  let volume = (audioRef.value as HTMLAudioElement).volume;
  // ➖
  if (type === 'volume-') {
    if (volume > 0) {
      (audioRef.value as HTMLAudioElement).volume = volume - 0.1 < 0.1 ? 0 : volume - 0.1;
    }
  } else if (type === 'volume+') {
    // ➕
    if (volume < 1) {
      (audioRef.value as HTMLAudioElement).volume = volume + 0.1 > 1 ? 1 : volume + 0.1;
    }
  } else {
    // 静音取消静音
    if (volume) {
      state.volume = volume;
      (audioRef.value as HTMLAudioElement).volume = 0;
    } else {
      (audioRef.value as HTMLAudioElement).volume = state.volume || 1;
    }
  }
  state.volumeB = parseInt((audioRef.value as HTMLAudioElement).volume * 100);
};

const handleVolumeChange = (e: any) => {
  (audioRef.value as HTMLAudioElement).volume = e.target.value / 100;
};

// 拖动进度条变化回调
const handleProgressChange = (e: any) => {
  audioRef.value.currentTime = (e.target.value / 100) * state.duration;
};

/**
 * @description 控制音乐播放
 * @param type 控制类型
 * @param isKeyEvent 是否是键盘事件
 * @param isHandlePlayed 是否是手动触发的播放/暂停
 */
const controlMusic = (type: string, isKeyEvent: boolean = false, isHandlePlayed = false) => {
  state.isHandlePlayed = isHandlePlayed;
  if (type === 'pause') {
    audioRef.value.pause();
    if (isKeyEvent) emits('playMusic', false);
  } else if (type === 'play') {
    audioRef.value.pause();
    setTimeout(() => {
      isUserInteraction.value = true;
      audioRef.value.play();
      if (isKeyEvent) emits('playMusic', true);
    }, 0);
  }
};

/**
 * @description 控制
 * @param type 控制类型
 * @param isHandlePlayed 是否是主动触发的播放/暂停
 */
const handleControl = (type: string, isHandlePlayed = false) => {
  if (type == 'pause' || type == 'play') {
    controlMusic(type, false, isHandlePlayed);
  } else if (type == 'volume-' || type == 'volume+' || type == 'mute') {
    controlVolume(type);
  } else if (type == 'prev') {
    isUserInteraction.value = true; // 已经交互过了
    state.isHandlePlayed = true; // 已经手动触发过了
    state.isPlaying = false;
    state.isLoading = true;
    if (state.currentIndex == 0) {
      state.currentIndex = musicList.value.length - 1;
    } else {
      state.currentIndex--;
    }
    state.currentMusic = musicList.value[state.currentIndex];
  } else if (type == 'next') {
    isUserInteraction.value = true; // 已经交互过了
    state.isHandlePlayed = true; // 已经手动触发过了
    state.isPlaying = false;
    state.isLoading = true;
    if (state.currentIndex == musicList.value.length - 1) {
      state.currentIndex = 0;
    } else {
      state.currentIndex++;
    }
    state.currentMusic = musicList.value[state.currentIndex];
  }
};

// 点击封面控制音乐播放/暂停
const handleCoverControl = () => {
  if (state.isPlaying) {
    handleControl('pause', true);
  } else {
    handleControl('play', true);
  }
};

// 键盘事件控制音乐播放 并做兼容性处理
const handleKeyupCallback = _.debounce((e: KeyboardEvent) => {
  const key = e.key.toLowerCase();
  // 组合键
  const groupKeys = e.ctrlKey && e.shiftKey;
  if ((groupKeys && key == 'arrowleft') || (groupKeys && key == 'left')) {
    handleControl('prev', true);
  } else if ((groupKeys && key == 'arrowright') || (groupKeys && key == 'right')) {
    handleControl('next', true);
  } else if ((groupKeys && key == 'arrowdown') || (groupKeys && key == 'down')) {
    handleControl('volume-');
  } else if ((groupKeys && key == 'arrowup') || (groupKeys && key == 'up')) {
    handleControl('volume+');
  } else if ((e.metaKey && e.altKey) || (e.altKey && e.metaKey)) {
    // mac 组合键 command + alt  windows组合键 win + alt
    if (isUserInteraction.value) {
      if (state.isPlaying) {
        controlMusic('pause', true, true);
      } else {
        controlMusic('play', true, true);
      }
    } else {
      CustomMessage({
        type: 'warning',
        msg: '请先对页面进行交互后再操作!'
      });
    }
  } else if (groupKeys && key == 'q') {
    router.push('/search');
  } else if (groupKeys && key == 'p') {
    emits('fullscreen');
  } else if (groupKeys && key == 'delete') {
    handleControl('mute');
  } else if (groupKeys && key == 'b') {
    window.open(getBackstageurl() + '/');
  } else if (groupKeys && key == 'l') {
    router.push('/play/mp3');
  } else if (groupKeys && key == ',') {
    router.push('/start');
  } else if (groupKeys && key == '.') {
    router.push('/');
  } else if (groupKeys && key == '/') {
    router.push('/about/me');
  }
}, 200);

// 当前歌曲播放结束回调
const endedCallback = () => {
  handleControl('next', true);
};

// 当前歌曲播放进度回调
const timeupdateCallback = () => {
  state.currentTime = audioRef.value.currentTime * 1;
  state.duration = audioRef.value.duration * 1;
  state.progress = parseInt((state.currentTime / state.duration) * 100) || 0;
};

// 当前歌曲音量变化回调
const volumechangeCallback = () => {
  if (audioRef.value.volume == 0) {
    state.isMute = true;
  } else {
    state.isMute = false;
  }
};

// 当前歌曲播放出错回调
const errorCallback = (err: any) => {
  console.warn('music player errorCallback', err);
};

// 当前歌曲可以播放回调
const canplayCallback = () => {
  state.isLoading = false;
  if (isUserInteraction.value && state.isHandlePlayed) controlMusic('play', false, true);
};

// 当前歌曲开始播放回调
const playingCallback = () => {
  state.isPlaying = true;
  state.isLoading = false;
};

// 当前歌曲暂停播放回调
const pauseCallback = () => {
  state.isPlaying = false;
};

// 控制播放是否悬浮
const handlePlayerTop = () => {
  store.SET_PLAYER_TOP(!store.playerTop);
  state.playerTop = store.playerTop;
};

onMounted(() => {
  audioRef.value.addEventListener('ended', endedCallback);
  audioRef.value.addEventListener('timeupdate', timeupdateCallback);
  audioRef.value.addEventListener('volumechange', volumechangeCallback);
  audioRef.value.addEventListener('error', errorCallback);
  audioRef.value.addEventListener('canplay', canplayCallback);
  audioRef.value.addEventListener('playing', playingCallback);
  audioRef.value.addEventListener('pause', pauseCallback);
  window.addEventListener('keydown', handleKeyupCallback);
});

onBeforeUnmount(() => {
  audioRef.value.removeEventListener('ended', endedCallback);
  audioRef.value.removeEventListener('timeupdate', timeupdateCallback);
  audioRef.value.removeEventListener('volumechange', volumechangeCallback);
  audioRef.value.removeEventListener('error', errorCallback);
  audioRef.value.removeEventListener('canplay', canplayCallback);
  audioRef.value.removeEventListener('playing', playingCallback);
  audioRef.value.removeEventListener('pause', pauseCallback);
  window.removeEventListener('keydown', handleKeyupCallback);
});

watch(
  () => props.currentMusicId,
  id => {
    if (id) {
      const index = musicList.value.findIndex(item => item.id == id);
      if (index !== -1) {
        state.currentIndex = index;
        state.currentMusic = musicList.value[index];
        state.isPlaying = false;
        state.isLoading = true;
        isUserInteraction.value = true;
        controlMusic('play', false, true);
      }
    }
  }
);

watch(
  () => state.isPlaying,
  n => {
    emits('music-status', n);
    $bus.emit('musicPlayerStatusChange', n);
    localStorage.setItem('isPlaying', n + '');
  }
);

watch(
  () => state.currentMusic,
  () => {
    $bus.emit('musicPlayerCurrentMusicChange', state.currentMusic.id);
    localStorage.setItem('currentMusicId', state.currentMusic.id);
  },
  { deep: true }
);

// 监听音乐列表变化
watch(
  () => store.musicList,
  () => {
    initGetMusicList();
  },
  { deep: true }
);

defineExpose({
  isUserInteraction
});
</script>

<style lang="scss" scoped>
.music-player-components-wrap {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  overflow: hidden;
  .cover-wrap {
    height: 120px;
    width: 100px;
    background-color: var(--bg-wrap-light-color);
    padding: 5px;
    border-radius: var(--border-radius-2);

    overflow: hidden;
    .cover-img-wrap {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: var(--bg-content-color);
      background-image: url('@/assets/images/bg/playing.jpg');
      background-size: 200% 100%;
      border-radius: var(--border-radius-2);
      padding: 5px;
      position: relative;
      .cover-img {
        border: 1px solid var(--text-color);
        width: 80px;
        height: 80px;
        border-radius: 50%;
      }
      .paly-pause {
        width: 80px;
        height: 80px;
        position: absolute;
        top: 16px;
        left: 5px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: transparent;
        border-radius: 50%;
        .iconfont {
          font-size: 30px;
          color: #eeeeee;
        }
        &:hover {
          .iconfont {
            color: var(--theme-light-color-5);
          }
        }
      }
    }
    .rotate-play {
      animation: spin 5s linear infinite;
    }
  }
  .contral-music-wrap {
    background-color: var(--bg-wrap-light-color);
    padding: 5px;
    border-radius: var(--border-radius-2);
    margin-left: 10px;
    width: 230px;
    height: 120px;
    .contral-music-content {
      width: 220px;
      padding: 0 5px;
      height: 110px;
      border-radius: var(--border-radius-2);
      display: flex;
      flex-direction: column;
      align-items: center;
      background-color: var(--bg-content-color);
      background-image: url('@/assets/images/bg/playing.jpg');
      background-size: cover;
      .music-name {
        height: 35px;
        font-size: 14px;
        line-height: 35px;
        color: var(--text-color);
        text-align: left;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
      }
      .contral-wrap {
        height: 25px;
        color: var(--text-color);
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 5px;
        .iconfont {
          font-size: 18px;
          margin: 0 10px;
          &:hover {
            color: var(--theme-light-color-5);
          }
        }
        .isTop {
          color: var(--theme-color);
        }
      }
      .custom-progress {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 25px;
        padding: 0 5px;
        width: 100%;
        .time {
          color: var(--text-color);
        }
        .volume-time {
          display: inline-block;
          width: 25px;
          text-align: right;
          color: var(--text-color);
        }
        .yin {
          display: flex;
          align-items: center;
          .iconfont {
            color: var(--text-color);
          }
        }
        input[type='range'] {
          -webkit-appearance: none;
          appearance: none;
          margin: 0;
          outline: 0;
          background-color: transparent;
          border-radius: 3px;
          width: 90px;
          margin-right: 10px;
        }
        /* 定义range控件轨道的样式 */
        [type='range']::-webkit-slider-runnable-track {
          height: 6px;
          background-color: var(--theme-light-color);
        }

        /* 定义range控件容器的样式 已激活 */
        [type='range' i]::-webkit-slider-container {
          height: 6px;
          background-color: var(--text-color);
          border-radius: 3px;
          overflow: hidden;
        }

        /* 定义range控件拇指的样式 当前值 */
        [type='range']::-webkit-slider-thumb {
          -webkit-appearance: none;
          appearance: none;
          width: 3px;
          height: 6px;
          border-radius: 50%;
          background-color: var(--theme-color);
          /* 使用border-image属性给拇指添加渐变边框 */
          border-image: linear-gradient(var(--theme-color), var(--theme-color)) 0 fill / 8 20 8 0 / 0px 0px 0 2000px;
        }
      }
      .progress-time {
        height: 25px;
        font-size: 12px;
        line-height: 25px;
      }
      .custom-volume {
        height: 30px;
        justify-content: center;
        input[type='range'] {
          width: 130px;
        }
      }
    }
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.empty-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: var(--text-color);
  font-size: 12px;
  img {
    width: 50px;
    height: 50px;
    margin-bottom: 10px;
  }
}
</style>

<style lang="scss">
.dark {
  .music-player-wrap {
    .contral-music-content {
      background-image: url('@/assets/images/bg/dark-playing.jpg') !important;
      background-size: 100% 100% !important;
    }
    .cover-img-wrap {
      background-image: url('@/assets/images/bg/dark-playing.jpg') !important;
    }
  }
}
</style>
